<script setup lang="ts">
  import { ref, defineEmits, computed, watch, onMounted } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import { searchLog, overLog, clearLog, goLog } from '@/api/system-basic';

  import * as XLSX from 'xlsx';
  import { saveAs } from 'file-saver';

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      width: 60,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '命令下发时间',
      dataIndex: 'orderTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 170,
      ellipsis: true,
      tooltip: true,
      fixed: 'left',
    },
    {
      title: '是否手动',
      dataIndex: 'remark',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '任务号',
      dataIndex: 'wmsTaskId',
      width: 140,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '操作类型',
      dataIndex: 'command',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '功能',
      dataIndex: 'result',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '移库任务',
      dataIndex: 'parentTaskId',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },

    {
      title: '任务类型',
      dataIndex: 'taskType',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '是否完成',
      dataIndex: 'isFinish',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '是否回库',
      dataIndex: 'isBack',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '巷道',
      dataIndex: 'roadway',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 110,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '开始位置',
      dataIndex: 'startCode',
      width: 140,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '结束位置',
      dataIndex: 'endCode',
      width: 140,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '命令执行开始时间',
      dataIndex: 'orderStartTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '命令执行结束时间',
      dataIndex: 'orderEndTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '货位确认时间',
      dataIndex: 'distributionRoadwayTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '操作盘编码',
      dataIndex: 'palletCode',
      width: 140,
      ellipsis: true,
      tooltip: true,
      fixed: 'right',
    },
  ];

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  // 表单查询数据
  const taskType = ref<string>('');
  const wmsTaskId = ref<string>('');
  const palletCode = ref<string>('');
  const startCode = ref<string>('');
  const endCode = ref<string>('');
  const isFinish = ref<string>('');
  const isBack = ref<string>('');
  const startDate = ref<string>('');
  const endDate = ref<string>('');

  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  // 发送搜索数据
  const flowQueryData = ref({
    searchParams: computed(() => ({
      taskType: taskType.value,
      wmsTaskId: wmsTaskId.value,
      palletCode: palletCode.value,
      startCode: startCode.value,
      endCode: endCode.value,
      isFinish: isFinish.value,
      isBack: isBack.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNumber.value,
    })),
    startDate: computed(() => startDate.value),
    endDate: computed(() => endDate.value),
  });
  // 表格数据
  const newData = ref<any>();
  async function handleSearch() {
    newData.value = await searchLog(flowQueryData.value);
    emit('updateArray', newData.value);
  }
  // 重置
  function reset() {
    taskType.value = '';
    wmsTaskId.value = '';
    palletCode.value = '';
    startCode.value = '';
    endCode.value = '';
    isFinish.value = '';
    isBack.value = '';
    startDate.value = '';
    endDate.value = '';
    handleSearch();
  }

  // 结束任务
  async function onOver() {
    if (
      !booleanStore.logList[0] ||
      booleanStore.logList[0].value.length === 0
    ) {
      Notification.error({
        title: '失败',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }

    const data = { msGkLogIds: booleanStore.logList[0].value };
    const res = await overLog(data);
    if (res.retCode) {
      if (res.retCode === '200') {
        Notification.success({
          title: '成功',
          content: '任务结束成功',
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: '任务结束失败',
          closable: true,
        });
      }
      handleSearch();
      booleanStore.toggleBool4(8);
    } else {
      Notification.error({
        title: '失败',
        content: '网络异常',
        closable: true,
      });
    }
  }
  // 清理任务
  async function onClear(record: any) {
    if (
      !booleanStore.logList[0] ||
      booleanStore.logList[0].value.length === 0
    ) {
      Notification.error({
        title: '失败',
        content: '请至少选择一条数据',
        closable: true,
      });

      return;
    }
    const data = { msGkLogIds: booleanStore.logList[0].value, type: 'data' };
    const res = await clearLog(data);
    if (res.retCode) {
      if (res.retCode === '200') {
        Notification.success({
          title: '成功',
          content: res.retMsg,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: res.retMsg,
          closable: true,
        });
      }
      handleSearch();
      booleanStore.toggleBool4(8);
    } else {
      Notification.error({
        title: '失败',
        content: '网络异常',
        closable: true,
      });
    }
  }
  // 下发任务
  async function onGo(record: any) {
    if (
      !booleanStore.logList[0] ||
      booleanStore.logList[0].value.length !== 1
    ) {
      Notification.error({
        title: '失败',
        content: '请选择一条数据',
        closable: true,
      });
      booleanStore.toggleBool4(8);
      return;
    }
    const data = { msGkLogId: booleanStore.logList[0].value[0] };
    const res = await goLog(data);
    if (res.retCode) {
      if (res.retCode === '200') {
        Notification.success({
          title: '成功',
          content: res.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: res.message,
          closable: true,
        });
      }
      handleSearch();
      booleanStore.toggleBool4(8);
    } else {
      Notification.error({
        title: '失败',
        content: '网络异常',
        closable: true,
      });
    }
  }

  onMounted(() => {
    handleSearch();
  });
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 47) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
  watch(
    () => booleanStore.update,
    () => {
      if (booleanStore.num6 === 20) handleSearch();
    }
  );

  // 导出excel
  // 导出参数
  function exportParam(excelData: any, excelColumns: any) {
    const emptyRows = Array(1).fill({});
    const dataWithEmptyRows = emptyRows.concat(excelData);
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(dataWithEmptyRows, {
      header: excelColumns.map((h: any) => h.dataIndex),
      skipHeader: true,
    });
    XLSX.utils.sheet_add_aoa(
      ws,
      [excelColumns.map((itemName: any) => itemName.title)],
      {
        origin: 'A1', // 表头开始的位置
      }
    );
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    saveAs(
      new Blob([wbout], { type: 'application/octet-stream' }),
      '日志查询.xlsx'
    );
  }
  // 导出
  async function exportExcel() {
    // 发送搜索数据
    const flowQueryData2 = ref({
      searchParams: computed(() => ({
        taskType: taskType.value,
        wmsTaskId: wmsTaskId.value,
        palletCode: palletCode.value,
        startCode: startCode.value,
        endCode: endCode.value,
        isFinish: isFinish.value,
        isBack: isBack.value,
      })),
      pageParameter: computed(() => ({
        rows: 1000000,
        page: pageNumber.value,
      })),
      startDate: computed(() => startDate.value),
      endDate: computed(() => endDate.value),
    });
    // 获取数据库满足的数据
    const data = await searchLog(flowQueryData2.value);

    if (data?.responseBody?.result.length === 0) {
      Notification.warning({
        title: '警告',
        content: '当然没有符合的数据导出',
        closable: true,
      });
      return;
    }
    // 根据列数据保留表数据，过滤多余的表格数据
    const filteredData = data?.responseBody?.result.map((item: any) => {
      const newItem: any = {};
      columns.forEach((columnIndex: any) => {
        if (columnIndex.dataIndex in item) {
          newItem[columnIndex.dataIndex] = item[columnIndex.dataIndex];
        }
      });
      return newItem;
    });
    exportParam(filteredData, columns);
  }
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-select
          v-model="taskType"
          allow-clear
          placeholder="任务类型"
          size="large"
        >
          <a-option value="1">入库</a-option>
          <a-option value="2">出库</a-option>
          <a-option value="3">移库</a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input
          v-model="wmsTaskId"
          allow-clear
          placeholder="任务ID"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input
          v-model="palletCode"
          allow-clear
          placeholder="托盘编码"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input
          v-model="startCode"
          allow-clear
          placeholder="开始位置"
          size="large"
        />
      </div>
    </a-col>
  </a-row>
  <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-input
          v-model="endCode"
          allow-clear
          placeholder="结束位置"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-select
          v-model="isFinish"
          allow-clear
          placeholder="完成状态"
          size="large"
        >
          <a-option value="Y">完成</a-option>
          <a-option value="N">未完成</a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-select
          v-model="isBack"
          allow-clear
          placeholder="回库状态"
          size="large"
        >
          <a-option value="Y">已回库</a-option>
          <a-option value="N">未回库</a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-date-picker
          v-model="startDate"
          style="width: 100%"
          placeholder="任务起始时间"
          size="large"
        />
      </div>
    </a-col>
  </a-row>
  <a-row class="margin-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-date-picker
          v-model="endDate"
          style="width: 100%"
          placeholder="任务结束时间"
          size="large"
        />
      </div>
    </a-col>
  </a-row>

  <div class="btn-group">
    <a-button type="primary" size="large" @click="handleSearch">查询</a-button>
    <a-button class="btn-reset" size="large" @click="reset">重置</a-button>
    <a-button type="primary" class="btn-reset" size="large" @click="onOver"
      >结束任务</a-button
    >
    <a-button type="primary" class="btn-reset" size="large" @click="onClear"
      >清理占位</a-button
    >
    <a-button type="primary" class="btn-reset" size="large" @click="onGo"
      >下发任务</a-button
    >
    <a-button type="primary" class="btn-reset" size="large" @click="exportExcel"
      >导出excel</a-button
    >
  </div>
</template>

<style scoped>
  .margin-top {
    margin-top: 10px;
  }
  .btn-group {
    float: right;
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
</style>
